<template>
  <div class="echarts-page">
    <div class="left-chart">
      <v-chart :option="leftOption"></v-chart>
    </div>
    <div class="right-chart">
      <v-chart :option="rightOption"></v-chart>
    </div>
  </div>
</template>

<script setup>
import { inject, ref, onMounted, computed } from 'vue'

const queryResultData = inject('queryResultData')

const leftOption = ref({})
const rightOption = ref({})

const typeData = computed(() => {
  const typeCount = {}
  queryResultData.value.forEach((item) => {
    typeCount[item.type] = (typeCount[item.type] || 0) + 1
  })
  return Object.keys(typeCount).map((key) => ({
    name: key,
    value: typeCount[key],
  }))
})
const levelData = computed(() => {
  const levelCount = {}
  const levelText = ['轻微事故', '一般事故', '严重事故', '灾难事故']
  queryResultData.value.forEach((item) => {
    levelCount[levelText[item.grade - 1]] = (levelCount[levelText[item.grade - 1]] || 0) + 1
  })
  return Object.keys(levelCount).map((key) => ({
    name: key,
    value: levelCount[key],
  }))
})
const renderChart = (option, { title = '', data = [] } = {}) => {
  option.value = {
    title: {
      text: title,
      left: 'left',
    },
    tooltip: {
      trigger: 'item',
      formatter: (params) => {
        return `
        ${params.marker + params.seriesName.slice(2, 4)}: ${params.name}</br>
        ${params.marker}次数: ${params.value}
        `
      },
    },
    legend: {
      // orient: 'vertical',
      left: 'center',
      top: 'bottom',
      formatter: (name) => {
        return name + ' | ' + data.find((item) => item.name === name).value
      },
      align: 'left', //标记和文本的对齐
    },
    series: [
      {
        name: title,
        type: 'pie',
        radius: '50%',
        data,
        label: {
          formatter: '{b} | {c}',
        },
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)',
          },
        },
      },
    ],
  }
}

onMounted(() => {
  renderChart(leftOption, { title: '事件类型分析', data: typeData.value })
  renderChart(rightOption, { title: '事件等级分析', data: levelData.value })
})
</script>

<style lang="scss" scoped>
.echarts-page {
  display: flex;
  gap: 10px;
  height: 420px;
  div {
    flex: 1;
  }
}
</style>
